<?php
/**                                          
 * 自定义标签解析
 * @author M2
 * @version 1.0
 * create Date 2013-07-08
 */
class TagLibYl extends TagLib{

	protected $comparison = array(
			'{notlike}' => 'NOT LIKE',
			'{notin}' => 'NOT IN',
			'{like}' => 'LIKE',
			'{eq}' => '=',
			'{neq}' => '<>',
			'{elt}' => '<=',
			'{egt}' => '>=',
			'{gt}' => '>',
			'{lt}' => '<',
			'{in}' => 'IN',
	);
	
	protected $tags = array (
			'import'=>array('attr'=>'file,href,type,value,basepath','close'=>0,'alias'=>'css,js'),
			'include' => array('attr'=>'file','close'=>0),
			'site' => array('attr'=>'siteid,field','close'=>0),
			'channel' => array('attr'=>'type,status'),
			'a' => array ('attr' => 'channelname,target,href,title,class,rel,style'),
			'image' => array('attr'=>'channelname,width,height','close'=>0),
			'content' => array('attr'=>'type,status'),
			'count' => array('attr'=>'type'),
			'contents' => array('attr'=>'channelname,key,mod,ispage,pagesize,sql','level'=>3),
			'channels' => array('attr'=>'channelname,upLevel','level'=>3),
			'location' => array(),
			'pageItem' => array('attr'=>'type,text,other'),
			'pageItems' => array('attr'=>''),
			'comment' => array('attr'=>'type','close'=>0),
			'comments' => array('attr'=>''),
			'block' => array('attr'=>'id,value,limit,order'),
			'sql' => array('attr'=>'name,field,limit,order,where,sql,key,mod,value','level'=>3),
			'searchInput' => array('attr'=>'styleName,searchUrl,openwin,inputName'),
			'searchOutput' => array('attr'=>''),
	);
	
	public function _import($attr,$content,$isFile=false,$type='') {
		$tag  = $this->parseXmlAttr($attr,'import');
		$file   = isset($tag['file'])?$tag['file']:$tag['href'];
		$parseStr = '';
		if($isFile) {
			// 根据文件名后缀自动识别
			$type = $type?$type:(!empty($tag['type'])?strtolower($tag['type']):null);
			// 文件方式导入
			$array =  explode(',',$file);
			foreach ($array as $val){
				if (!$type || isset($reset)) {
					$type = $reset = strtolower(substr(strrchr($val, '.'),1));
				}
				switch($type) {
					case 'js':
						$parseStr .= '<script type="text/javascript" src="'.SITE_URL.'/'.$val.'"></script>';
						break;
					case 'css':
						$parseStr .= '<link rel="stylesheet" type="text/css" href="'.SITE_URL.'/'.$val.'" />';
						break;
					case 'php':
						$parseStr .= '<?php require_cache("'.SITE_URL.'/'.$val.'"); ?>';
						break;
				}
			}
		}
		return $parseStr;
	}
	// import别名使用 导入css文件 <css file="__PUBLIC__/Css/Base.css" />
	public function _css($attr,$content) {
		return $this->_import($attr,$content,true,'css');
	}
	
	// import别名使用 导入js文件 <js file="__PUBLIC__/Js/Base.js" />
	public function _js($attr,$content) {
		return $this->_import($attr,$content,true,'js');
	}
	
	public function _include($attr,$content) {
		$tag = $this->parseXmlAttr($attr,'include');
		$sid = $this->tpl->get('sid');
		$templatePath = D('Site')->getSiteInfo($sid);
		$templatePath .= 'templates/';
		if(substr($tag['file'],0,3)=='../') {
			$filename = str_replace('../',$templatePath,$tag['file']);
		} elseif(substr($tag['file'],0,3)<>'../' &&  substr($tag['file'],0,2)=='./') {
			$filename = SITE_PATH.substr($tag['file'],1,strlen($tag['file']));
		} else {
			$filename = $templatePath.$tag['file'];
		}
		$filename = iconv("UTF-8","GB2312",$filename);
		if(!file_exists($filename)) return '模板文件:'.$filename.'不存在!';
		$parseStr  = $this->tpl->parse(read_file($filename));
		return $parseStr;
	}
	
	public function _site($attr,$content) {
		$tag = $this->parseXmlAttr($attr,'site');
		$siteid = $tag['siteid'];
		$field = empty($tag['field'])?'domain':$tag['field'];
		$parseStr = '<?php $siteid='.$siteid.';$data["siteid"] = $siteid;';
		$parseStr .= '$site = M("cms_site")->where($data)->find();';
		$parseStr .= 'if(is_array($site)): echo $site["'.$field.'"];?>';
		$parseStr .= '<?php endif;?>';
		if(!empty($parseStr)) {
			return $parseStr;
		}
		return ;
	}
	
	public function _location($attr,$content) {
		global $cmstag;
		if(!empty($cmstag['contentInfo']['cid'])) {
			$pid = $cmstag['contentInfo']['cid'];
		} else {
			$pid = $cmstag['contentlist']['id'];
		}
		$siteid = $this->tpl->get('sid');
		$data['siteid'] = $siteid;
		$parseStr = '';
		$findZhu = M('cms_site')->where('status=1')->find();
		$currentSite = M('cms_site')->where($data)->find();
		if($currentSite['siteid'] == $findZhu['siteid']) {
			$parseStr[] = "<a href='".$currentSite['domain']."'>{$currentSite['name']}</a>";
		} else {
			$parseStr[] = "<a href='".$findZhu['domain']."'>{$findZhu['name']}</a>";
			$parseStr[] = "<a href='".$currentSite['domain']."'>{$currentSite['name']}</a>";
		}
		$list = M('cms_category')->field("concat(plistid,'-',id) as bpath")->where(array('id'=>$pid))->find();
		$map['id'] = array('in',strtr(ltrim($list['bpath'],'0-'),array('-'=>',')));
		$map['pid'] = array('neq',0);
		$list = M('cms_category')->field("concat(plistid,'-',id) as bpath,cname,id,createurl,catenaming,artnaming")->where($map)->order('bpath')->select();
		$domain = $currentSite['domain'].'/';
		foreach($list as $k=>$v) {
			if(empty($v['createurl'])) {
				$v['catenaming'] = common('Array')->getParseTemplate($v,$v['catenaming'],'cateid');
				$domain .= $v['catenaming'];
			} else {
				$domain .= $v['createurl'];
			}
			$parseStr[] = "<a href='".$domain."'>{$v['cname']}</a>";
		}
		if(!empty($cmstag['contentInfo']['id'])) {
			$clist = M('cms_category')->where("id={$cmstag['contentInfo']['cid']}")->find();
			$artnaming = common('Array')->getParseTemplate($cmstag['contentInfo'],$clist['artnaming'],'contentid');
			$parseStr[] = $cmstag['contentInfo']['title'];
		}
		$parseStr = implode('&nbsp;>&nbsp;',$parseStr);
		return $parseStr;
	}
	
	/**
     +----------------------------------------------------------
     * a标签解析
     * 格式：
     * <Yl:a channelname="测试栏目1" target="_blank"></Yl:a>
     * 获取栏目名称为测试栏目1的栏目链接，显示文字为栏目名称
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $attr 标签属性
     * @param string $content  标签内容
     +----------------------------------------------------------
     * @return string|void
     +----------------------------------------------------------
     */
	public function _a($attr, $content) {
		$tag = $this->parseXmlAttr ( $attr, 'a' );
		$parseStr = '<a ';
		if(!empty($tag['channelname'])) {
			$channelName = $tag['channelname'];
			$findChannel = M('cms_category as a')->join(C('DB_PREFIX').'cms_site as site on site.siteid=a.siteid')
				->field('a.cname,a.url,a.imageurl,concat(site.domain,"/",IF(LENGTH(trim(a.createurl))<1,
						IF(a.catenaming like "%{cateid}%",replace(a.catenaming,"{cateid}",a.id),a.catenaming),a.createurl)) as channelurl')
				->where("a.cname='".$channelName."'")->find();
			if($findChannel) {
				if(!empty($findChannel['url']))
					$tag['href'] = $findChannel['url'];
				else
					$tag['href'] = $findChannel['channelurl'];
				$title = $findChannel['cname'];
				$var = $findChannel['cname'];
			}
		}
		if(!empty($tag['title'])) 
			$parseStr .= "title='{$tag['title']}' ";
		elseif(isset($title) && !empty($title))
			$parseStr .= "title='$title' ";
		if(!empty($tag['href'])) {
			$parseStr .= "href='{$tag['href']}' ";
		} elseif(!empty($tag['type'])) {
			if($tag['type'] == 'channels')
				$parseStr .= "href='".'<?php echo !empty($channels["url"])?$channels["url"]:$channels["channelurl"];?>'."' ";
			elseif($tag['type'] == 'contents')
				$parseStr .= "href='".'<?php echo !empty($field["url"])?$field["url"]:$field["picurl"];?>'."' ";
		}
		
		if(!empty($tag['target'])) 		$parseStr .= "target='{$tag['target']}' ";
		if(!empty($tag['class']))		$parseStr .= "class='{$tag['class']}' ";
		if(!empty($tag['style'])) 		$parseStr .= "style='{$tag['style']}' ";
		
		$parseStr .= '>';
		
		if(!empty($content)) {
			$parseStr .= $content;
		} elseif(isset($var) && !empty($var)) {
			$parseStr .= $var;
		} elseif(!empty($tag['type'])) {
			if($tag['type'] == 'channels')
				$parseStr .= '<?php echo $channels["cname"];?>';
			elseif($tag['type'] == 'contents')
				$parseStr .= '<?php echo $field["title"];?>';
		}
		$parseStr .= '</a>';
		return $parseStr;
	}
	/**
	 +----------------------------------------------------------
	 * image标签解析
	 * 格式：
	 * <Yl:image channelname="测试栏目1" width="200" height="100" />
	 * 获取栏目名称为测试栏目1的栏目图片
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param string $attr 标签属性
	 * @param string $content  标签内容
	 +----------------------------------------------------------
	 * @return string|void
	 +----------------------------------------------------------
	 */
	public function _image($attr,$content) {
		$tag = $this->parseXmlAttr($attr,'image');
		$parseStr = '<img ';
		if(!empty($tag['channelname'])) {
			$channelName = $tag['channelname'];
			$findChannel = M ( 'cms_category' )->where ( "cname='$channelName'" )->find ();
			if($findChannel) {
				if(substr($findChannel['imageurl'],0,7) !== 'http://' && substr($findChannel['imageurl'],0,8) !== 'https://') {
					$u = SITE_URL.'/';
				} else {
					$u = '';
				}
				$tag['href'] = $u.$findChannel['imageurl'];
				$var = $findChannel['cname'];
			}
		}
		if(!empty($tag['src'])) {
			$parseStr .= "src='".$tag['src']."' ";
		} elseif(!empty($tag['href'])) {
			$parseStr .= "src='".$tag['href']."' ";
		} elseif(!empty($tag['type'])) {
			if($tag['type'] == 'channels')
				$parseStr .= "src='".
					'<?php if(substr($channels["imageurl"],0,7) !== "http://" && substr($channels["imageurl"],0,8) !== "https://") {
							$u = SITE_URL."/";	
						} else {
							$u = "";
						}
						echo $u.$channels["imageurl"];?>'."' ";
			elseif($tag['type'] == 'contents')
				$parseStr .= "src='".'<?php if(substr($field["imageurl"],0,7) !== "http://" && substr($field["imageurl"],0,8) !== "https://") {
							$u = SITE_URL."/";
						} else {
							$u = "";
						}
						 echo $u.$field["imageurl"];?>'."' ";
		}
		if(!empty($tag['width'])) $parseStr .= "width='{$tag['width']}' ";
		if(!empty($tag['height'])) $parseStr .= "height='{$tag['height']}' ";
		$parseStr .= '/>';
		return $parseStr;
	}
	
	/**
	 +----------------------------------------------------------
	 * 文章显示类型标签解析
	 * 格式：
	 * <Yl:content type="title"></Yl:content>
	 * 此标签不做为单独使用，配合<Yl:contents></Yl:contents>使用,type='title'显示文章标题
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param string $attr 标签属性
	 * @param string $content  标签内容
	 +----------------------------------------------------------
	 * @return string|void
	 +----------------------------------------------------------
	 */
	public function _content($attr,$content) {
		$tag = $this->parseXmlAttr($attr,'content');
		if(!empty($tag['type'])) {
			if(!empty($tag['status'])) {
				$content = $this->tpl->get('content');
				$contentId = $content['id'];
				if($contentId) {
					$parseStr .= '<?php $data["id"]='.$contentId.';';
					$parseStr .= '$content=M("cms_article")->field(siteid,cid,classid,title,url,imageurl,keywords,description,content,readpoint)->where($data)->find();';
					$parseStr .= 'if(is_array($content)): echo $content["'.$tag['type'].'"];?>';
					$parseStr .= '<?php endif;?>';
				}
			} else {
				$parseStr = '<?php echo $field["'.$tag['type'].'"]; ?>';
			}
		}
		return $parseStr;
	}
	
	/**
	 +----------------------------------------------------------
	 * 统计标签解析
	 * 格式：
	 * <Yl:count type="comments"></Yl:count>
	 * 统计文章评论数
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param string $attr 标签属性
	 * @param string $content  标签内容
	 +----------------------------------------------------------
	 * @return string|void
	 +----------------------------------------------------------
	 */
	public function _count($attr,$content) {
		$tag = $this->parseXmlAttr($attr,'count');
		$parseStr = '';
		if(!empty($tag['type'])) {
			//获取文章评论数
			if(strtolower($tag['type']) == 'comments') {
				$parseStr .= '<?php ';
				$parseStr .= '$artid = $field["id"];'; //获取文章id
				$parseStr .= 'if(!empty($artid)):';
				$parseStr .= '$sql = "SELECT COUNT(*) AS count FROM `yl_cms_comments` WHERE comment_id=$artid LIMIT 1";';
				$parseStr .= '$count = M()->query($sql);?>';
				$parseStr .= '<?php echo $count[0]["count"];?>';
				$parseStr .= '<?php endif;?>';
			}
		}
		return $parseStr;
	}
	
	/**
	 +----------------------------------------------------------
	 * 文章标签解析
	 * 格式：
	 * <Yl:contents channelname="测试栏目1" width="80%" ispage="1" pagesize="1">
	 * 		<Yl:a target="_blank"></Yl:a>
 	 * 		<Yl:image width="200" height="200" />
	 * 		<Yl:a target="_blank" title="{$field.url}">
	 * 			<Yl:image width="200" height="100" />
	 * 		</Yl:a>
	 * 		<Yl:a target="_blank">
	 * 			<Yl:content type="title"></Yl:content>
	 * 		</Yl:a>
	 * </Yl:contents>
	 * 获取栏目名称为测试栏目1下的文章列表
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param string $attr 标签属性
	 * @param string $content  标签内容
	 +----------------------------------------------------------
	 * @return string|void
	 +----------------------------------------------------------
	 */
	public function _contents($attr,$content) {
		$tag = $this->parseXmlAttr($attr,'contents');
		$key  		  =    !empty($tag['key']) ? $tag['key']:'i';
		$mod  		  =    isset($tag['mod']) ? $tag['mod']:'2';
		$ispage 	  =    isset($tag['ispage'])?$tag['ispage']:'';
		$pagesize 	  =    isset($tag['pagesize'])?$tag['pagesize']:20; //每页显示多少条
		$limits		  =    !empty($tag['limit'])?$tag['limit']:10;
		global $cmstag;
		$sql = 'SELECT concat(site.domain,'.'"/"'.',IF(LENGTH(trim(category.createurl))<1,site.dirname,category.createurl),
				IF(category.artnaming like "%{cateid}%" or category.artnaming like "%{contentid}%",
				replace(replace(category.artnaming, "{cateid}", category.id),"{contentid}",article.id),category.artnaming)) as picurl,
		concat(site.domain,'.'"/"'.',IF(LENGTH(trim(category.createurl))<1,site.dirname,category.createurl),replace(category.catenaming, "{cateid}", article.cid)) as channelurl,
		article.id as id,article.url as url,article.content as content,article.updatetime as updatetime,article.readpoint as readpoint,article.imageurl as
		imageurl,article.title as title,article.description as description,category.content as catecontent,category.cname as cname FROM yl_cms_article article
		LEFT JOIN yl_cms_category category ON article.cid=category.id LEFT JOIN yl_cms_site site ON category.siteid=site.siteid ';
		if(!empty($tag['channelname'])) {
			$sql .= $this->getSql($tag['channelname'],$tag['ispage'],$pagesize,1,$limits);
		} elseif(!empty($tag['type'])) {
            $tag['type'] = strtolower($tag['type']);
            if($tag['type'] == 'hot') {
                $sql .= 'where article.status="1" and article.is_hot = 1 order by article.updatetime desc,article.readpoint desc limit 0,'.$limits;
            }
            if($tag['type'] == 'recommend') {
                $sql .= 'where article.status="1" and article.is_recommend = 1 order by article.updatetime desc limit 0,'.$limits;
            }
            if($tag['type'] == 'color') {
                $sql .= 'where article.status="1" and article.is_color = 1 order by article.updatetime desc limit 0,'.$limits;
            }
            if($tag['type'] == 'top') {
                $sql .= 'where article.status="1" and article.is_top = 1 order by article.updatetime desc limit 0,'.$limits;
            }
        } else {
			if(!empty($cmstag['contentlist'])) {
				//$v = array_pop($cmstag['contentlist']);
				$current = isset($cmstag['page']['channels'][$cmstag['contentlist']['id']]['current'])?intval($cmstag['page']['channels'][$cmstag['contentlist']['id']]['current']):1;
				$sql .= $this->getSql($cmstag['contentlist']['cname'],$tag['ispage'],$pagesize,$current);
			}
			if(!empty($cmstag['contentInfo'])) {
				$sql = 'select * from '.C('DB_PREFIX').'cms_article where id='.$cmstag['contentInfo']['id'];
			}
		}
		if(!empty($tag['sql'])) {
			$sql = $this->parseSqlCondition($tag['sql']);
		}
		$parseStr = '<?php ';
		$parseStr .= '$__LIST__ = M()->query(\''.$sql.'\');';
		$parseStr .= 'if(is_array($__LIST__)): $'.$key.' = 0;';
		$parseStr .= 'foreach($__LIST__ as $key=>$field): ';
		$parseStr .= '$mod = ($'.$key.' % '.$mod.' );';
		$parseStr .= '++$'.$key.';?>';
		$parseStr .= $this->tpl->parse($content);
		$parseStr .= '<?php endforeach; endif;?>';
		if(!empty($parseStr)) {
			return $parseStr;
		}
		return ;
	}
	
	private function getPageInfo($totalRows,$pagesize,$current) {
		$nowPage = $current;
		$totalPage = ceil($totalRows/$pagesize); //总页数
		if($nowPage >= $totalPage) $nowPage = $totalPage; //如果当前页大于总页数，就让当前页=总页数
		if($nowPage<=1) $nowPage = 1; //如果当前页小于1，当前页=1
		$start = $pagesize * ($nowPage -1);
		$end = $pagesize;
		$GLOBALS['cmstag']['page']['channels']['pagesize'] = $pagesize;
		$GLOBALS['cmstag']['page']['channels']['count'] = $totalRows;
		$limit = $start.','.$end;
		return $limit;
	}
	private function getSql($channelname,$ispage,$pagesize,$current,$limit) {
		$sql = '';
		if($ispage == '1') {
			if(strpos($channelname,'.') !== false) {
				$channelname = $this->autoBuildVar($channelname);
				$sqlcount = 'select count(1) as count from '.C('DB_PREFIX').'cms_category as cate,'.C('DB_PREFIX').'cms_article as art where
						cate.id=art.cid and cate.cname="\'.'.$channelname.'.\'"';
			} else {
				$sqlcount = 'select count(1) as count from '.C('DB_PREFIX').'cms_category as cate,'.C('DB_PREFIX').'cms_article as art where
						cate.id=art.cid and cate.cname="'.$channelname.'"';
			}
			$result = M()->query($sqlcount);
			$count = $result[0]['count'];
			$limit = $this->getPageInfo($count,$pagesize,$current);
		}
		if(strpos($channelname,'.') !== false) {
			$channelname = $this->autoBuildVar($channelname);
			$sql .= 'where category.cname="\'.'.$channelname.'.\'"';
		} else {
			$sql .= 'where category.cname="'.$channelname.'"';
		}
		if(!empty($limit)) {
			$sql .= ' limit '.$limit;
		}
		return $sql;
	}
	/**
	 +----------------------------------------------------------
	 * 栏目属性标签解析
	 * 格式：
	 * <Yl:channel type="cname"></Yl:channel>
	 * 显示栏目下的栏目名称
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param string $attr 标签属性
	 * @param string $content  标签内容
	 +----------------------------------------------------------
	 * @return string|void
	 +----------------------------------------------------------
	 */
	public function _channel($attr,$content) {
		$tag = $this->parseXmlAttr($attr,'channel');
		if(!empty($tag['type'])) {
			if(!empty($tag['status'])) {
				$channel = $this->tpl->get('channel');
				$channelId = $channel['id'];
				if($channelId) {
					$parseStr = '<?php $data["id"]='.$channelId.';';
					$parseStr .= '$channel=M("cms_category")->field(siteid,pid,plistid,cname,url,imageurl,keywords,description,content)->where($data)->find();';
					$parseStr .= 'if(is_array($channel)): echo $channel["'.$tag['type'].'"];?>';
					$parseStr .= '<?php endif;?>';
				}
			} else {
				$parseStr = '<?php echo $channels["'.$tag['type'].'"]; ?>';
			}
		}
		return $parseStr;
	}
	/**
	 +----------------------------------------------------------
	 * 栏目标签解析
	 * 格式：
	 * <Yl:channels channelname="测试栏目1">
	 * 		<img src="./data/uploads/avatar/1/original.jpg" />
	 * 		<Yl:a target="_blank" title="xxx"></Yl:a>
	 * 		<Yl:channel type="cname"></Yl:channel>
	 * 		<Yl:image width="200" height="300" />
	 * </Yl:channels>
	 * 获取栏目名称为测试栏目1下的子栏目列表链接
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param string $attr 标签属性
	 * @param string $content  标签内容
	 +----------------------------------------------------------
	 * @return string|void
	 +----------------------------------------------------------
	 */	
	public function _channels($attr,$content) {
		static $_iterateParseCache = array();
		$cacheIterateId = md5('_channels'.$attr.$content);
		if(isset($_iterateParseCache[$cacheIterateId]))
			return $_iterateParseCache[$cacheIterateId];
		$tag = $this->parseXmlAttr($attr,'channles');
		$key  		  =    !empty($tag['key']) ? $tag['key']:'i';
		$mod  		  =    isset($tag['mod']) ? $tag['mod']:'2';
		
		if(!empty($tag['channelname'])) {
			$channelname = $tag['channelname'];
			$sql = 'select a.cname,a.url,a.imageurl,a.content,a.keywords,a.description,
					concat(site.domain,'.'"/"'.',IF(LENGTH(trim(a.createurl))<1,site.dirname,substring(a.createurl,2)),
					IF(a.catenaming like "%{cateid}%",replace(a.catenaming, "{cateid}", a.id),a.catenaming)) as channelurl
					from '.C('DB_PREFIX').'cms_category a,'.C('DB_PREFIX').'cms_category b LEFT JOIN 
					'.C('DB_PREFIX').'cms_site as site ON site.siteid = b.siteid where a.pid = b.id and b.cname="'.$channelname.'"';
		} elseif(isset($tag['uplevel'])) {
			if($tag['uplevel'] == '0') {
				$sql = 'SELECT cname,url,imageurl,content,keywords,description
						concat(site.domain,'.'"/"'.',IF(LENGTH(trim(createurl))<1,site.dirname,substring(createurl,2)),
						IF(catenaming like "%{cateid}%",replace(catenaming, "{cateid}", id),catenaming)) as channelurl FROM
						'.C('DB_PREFIX').'cms_category as category LEFT JOIN '.C('DB_PREFIX').'cms_site as site
						ON site.siteid = category.siteid WHERE pid="1"';
			}
		} else {
			$cateids = $tag['cateid'];
			$parseStr = '<?php $x='.$cateids.';$data["id"]=$x;';
			$parseStr .= '$channels=M("cms_category")->where($data)->find();';
			$parseStr .= 'if(is_array($channels)): ?>';
			$parseStr .= $this->tpl->parse($content);
			$parseStr .= '<?php endif;?>';
			return $parseStr;
		}
		$parseStr = '<?php ';
		$parseStr .= '$__LIST__=M()->query(\''.$sql.'\');';
		$parseStr .= 'if(is_array($__LIST__)):$'.$key.' =0;';
		$parseStr .= 'foreach($__LIST__ as $key=>$channels): ';
		$parseStr .= '$mod = ($'.$key.' % '.$mod.');';
		$parseStr .= '++$'.$key.';?>';
		$parseStr .= $this->tpl->parse($content);
		$parseStr .= '<?php endforeach; endif;?>';
		$_iterateParseCache[$cacheIterateId] = $parseStr;
		if(!empty($parseStr)) {
			return $parseStr;
		}
		return ;
	}
	/**
     +----------------------------------------------------------
     * 分页标签解析
     * 格式：
     * <Yl:pageItems>
     * 		<div class="pages">
     * 			<Yl:pageItem type="FirstPage" text="首页"></Yl:pageItem>
     * 			<Yl:pageItem type="PreviousPage" text="上一页" ></Yl:pageItem>
     * 			<Yl:pageItem type="PageNavigation"></Yl:pageItem>
     * 			<Yl:pageItem type="NextPage" text="下一页" ></Yl:pageItem>
     * 			<Yl:pageItem type="LastPage" text="尾页" ></Yl:pageItem>
     * 			<Yl:pageItem type="JumpPage" text="跳转到"></Yl:pageItem>
     * 		</div>
     * </Yl:pageItems>
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $attr 标签属性
     * @param string $content  标签内容
     +----------------------------------------------------------
     * @return string|void
     +----------------------------------------------------------
     */
	public function _pageItem($attr,$content) {
		global $cmstag;
		$tag = $this->parseXmlAttr ( $attr, 'pageItem' );
		$type = !empty($tag['other'])?$tag['other']:'channels';
		if($type == 'channels') {
			$count = isset($cmstag ['page']['channels']['count'])?intval ( $cmstag ['page']['channels']['count'] ):0;
			$pagesize = isset($cmstag['page']['channels']['pagesize'])?intval ( $cmstag ['page']['channels']['pagesize'] ):0;
			// 当前页
			$nowPage = !empty($cmstag['page']['channels'][$cmstag['contentlist']['id']]['current'])?intval($cmstag['page']['channels'][$cmstag['contentlist']['id']]['current']):1;
			$catenaming = common('Array')->getParseTemplate($cmstag['contentlist'],$cmstag['contentlist']['catenaming'],'cateid');
			if(!empty($catenaming)) {
				$arr = explode('.',$catenaming);
				$url = $arr[0];
				$prex = $arr[1];
				if(!empty($tag['type'])) {
					$parseStr = '<?php echo getPage('.$count.','.$pagesize.',' . $tag['type'] . ','.$nowPage.',"'.$url.'",'.$prex.',"'.$tag['text'].'");?>';
				}
			}
		}
		return $parseStr;
	}
	/**
	 +----------------------------------------------------------
	 * 分页标签解析
	 * 格式：
	 * <Yl:pageItems>
	 * </Yl:pageItems>
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param string $attr 标签属性
	 * @param string $content  标签内容
	 +----------------------------------------------------------
	 * @return string|void
	 +----------------------------------------------------------
	 */
	public function _pageItems($attr,$content) {
		$tag = $this->parseXmlAttr($attr,'pageItems');
		$parseStr = $content;
		return $parseStr;
	}
	/**
	 +----------------------------------------------------------
	 * 评论标签解析
	 * 格式：
	 * <Yl:comment>
	 * </Yl:comment>
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param string $attr 标签属性
	 * @param string $content  标签内容
	 +----------------------------------------------------------
	 * @return string|void
	 +----------------------------------------------------------
	 */
	public function _comment($attr,$content) {
		$tag = $this->parseXmlAttr($attr,'comment');
		if(!empty($tag['type'])) {
			if(strtolower($tag['type']) == 'username') {
				$parseStr = '<?php echo $comments["author"];?>';
			}
			if(strtolower($tag['type']) == 'ip') {
				$parseStr = '<?php echo $comments["author_ip"];?>';
			}
			if(strtolower($tag['type']) == 'datetime') {
				$parseStr = '<?php echo date("Y-m-d",$comments["commenttime"]);?>';
			}
			if(strtolower($tag['type']) == 'content') {
				$parseStr = '<?php echo $comments["content"];?>';
			}
			if(strtolower($tag['type']) == 'id') {
				$parseStr = '<?php echo $comments["id"];?>';
			}
		}
		return $parseStr;
	}
	/**
	 +----------------------------------------------------------
	 * 评论标签解析
	 * 格式：
	 * <Yl:comments>
	 * </Yl:comments>
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param string $attr 标签属性
	 * @param string $content  标签内容
	 +----------------------------------------------------------
	 * @return string|void
	 +----------------------------------------------------------
	 */
	public function _comments($attr,$content) {
		$tag = $this->parseXmlAttr($attr,'comments');
		global $cmstag;
		if(isset($cmstag)) {
			$contentId = $cmstag['contentInfo']['id'];
			$sql = M('cms_comments')->where("comment_id=$contentId")->select(false);
			$parseStr = '<?php ';
			$parseStr .= '$__LIST__=M()->query(\''.$sql.'\');';
			$parseStr .= 'if(is_array($__LIST__)):$i =0;';
			$parseStr .= 'foreach($__LIST__ as $key=>$comments): ';
			$parseStr .= '$mod = ($i % 2);';
			$parseStr .= '++$i;?>';
			$parseStr .= $this->tpl->parse($content);
			$parseStr .= '<?php endforeach; endif;?>';
			return $parseStr;
		} else {
			return ;
		}
	}
	/**
	 +----------------------------------------------------------
	 * 区块标签解析
	 * 格式：
	 * <Yl:block>
	 * </Yl:block>
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param string $attr 标签属性
	 * @param string $content  标签内容
	 +----------------------------------------------------------
	 * @return string|void
	 +----------------------------------------------------------
	 */
	public function _block($attr,$content) {
		static $_iterateParseCache = array();
		$cacheIterateId = md5('_block'.$attr.$content);
		if(isset($_iterateParseCache[$cacheIterateId]))
			return $_iterateParseCache[$cacheIterateId];
		$tag = $this->parseXmlAttr($attr,'block');
		$id			  =    isset($tag['id'])?$tag['id']:0;
		$key  		  =    !empty($tag['key']) ? $tag['key']:'i';
		$mod  		  =    isset($tag['mod']) ? $tag['mod']:'2';
		$value		  =    !empty($tag['value'])?$tag['value']:'block';
		$limit 		  =	   !empty($tag['limit'])?$tag['limit']:1;
		$order 		  =	   !empty($tag['order'])?$tag['order']:'updatetime desc';
		
		$findBlock = M('cms_block')->where("id=$id")->field('content_number')->find();
		if($findBlock) {
			$data['id'] = array('in',$findBlock['content_number']);
			$sql = M('cms_article')->where($data)->order($order)->limit('0,'.$limit)->select(false);
			$parseStr = '<?php ';
			$parseStr .= '$__LIST__=M()->query(\''.$sql.'\');';
			$parseStr .= 'if(is_array($__LIST__)):$'.$key.' =0;';
			$parseStr .= 'foreach($__LIST__ as $key=>$'.$value.'): ';
			$parseStr .= '$mod = ($'.$key.' % '.$mod.');';
			$parseStr .= '++$'.$key.';?>';
			$parseStr .= $this->tpl->parse($content);
			$parseStr .= '<?php endforeach; endif;?>';
			$_iterateParseCache[$cacheIterateId] = $parseStr;
		}
		if(!empty($parseStr)) {
			return $parseStr;
		}
		return ;
	}
	/**
	 +----------------------------------------------------------
	 * sql标签解析
	 * 格式：
	 * <Yl:sql sql="">
	 * </Yl:sql>
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param string $attr 标签属性
	 * @param string $content  标签内容
	 +----------------------------------------------------------
	 * @return string|void
	 +----------------------------------------------------------
	 */
	public function _sql($attr,$content) {
		static $_iterateParseCache = array();
		$cacheIterateId = md5('_sql'.$attr.$content);
		if(isset($_iterateParseCache[$cacheIterateId]))
			return $_iterateParseCache[$cacheIterateId];
		$tag = $this->parseXmlAttr($attr,'sql');
		$key = !empty($tag['key'])?$tag['key']:'i';
		$mod = isset($tag['mod'])?$tag['mod']:'2';
		$value = !empty($tag['value'])?$tag['value']:'sql';
		if($tag['name']) {
			$tag['where'] = $this->parseSqlCondition($tag['where']);
			$sql  = "M('{$tag['name']}')->";
			$sql .= ($tag['field'])?"field({$tag['field']})->":'';
			$sql .= ($tag['order'])?"order({$tag['order']})->":'';
			$sql .= ($tag['where'])?"where({$tag['where']})->":'';
			$sql .= ($tag['limit'])?"limit({$tag['limit']})->":'';
			$sql .= "select()";
		} else{
			if (!$tag['sql']) return '';
			$tag['sql'] = $this->parseSqlCondition($tag['sql']);
			$sql .= "M()->query('{$tag['sql']}')";
		}
		$parseStr = '<?php ';
		$parseStr .= '$__LIST__='.$sql.';';
		$parseStr .= 'if(is_array($__LIST__)):$'.$key.' =0;';
		$parseStr .= 'foreach($__LIST__ as $key=>$'.$value.'): ';
		$parseStr .= '$mod = ($'.$key.' % '.$mod.');';
		$parseStr .= '++$'.$key.';?>';
		$parseStr .= $this->tpl->parse($content);
		$parseStr .= '<?php endforeach; endif;?>';
		$_iterateParseCache[$cacheIterateId] = $parseStr;
		if(!empty($parseStr)) {
			return $parseStr;
		}
		return ;
	}
	/**
	 +----------------------------------------------------------
	 * 搜索表单标签解析
	 * 格式：
	 * <Yl:searchInput styleName="" searchUrl="" openwin="">
	 * </Yl:searchInput>
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param string $attr 标签属性
	 * @param string $content  标签内容
	 +----------------------------------------------------------
	 * @return string|void
	 +----------------------------------------------------------
	 */
	public function _searchInput($attr,$content) {
		$tag = $this->parseXmlAttr($attr,'searchInput');
		$styleName = empty($tag['stylename'])?'搜索':$tag['stylename'];
		$searchUrl = empty($tag['searchurl'])?URL('admin/Search/search'):$tag['searchurl'];
		$inputName = empty($tag['inputname'])?'word':$tag['inputname'];
		$openwin   = empty($tag['openwin'])?true:$tag['openwin'];
		$pageNum   = empty($tag['pagenum'])?20:$tag['pagenum'];
		$target = $openwin === 'false'?'_self':'_blank';
		$parseStr = '<form id="form1" action="'.$searchUrl.'" method="post" target="'.$target.'">';
		$parseStr .= '<input type="text" name="'.$inputName.'" id="'.$inputName.'" />';
		$parseStr .= '<input type="hidden" name="pagenum" id="pagenum" value="'.$pageNum.'" />';
		$parseStr .= '<input type="submit" value="'.$styleName.'" />';
		$parseStr .= '</form>';
		return $parseStr;
	}
	/**
	 +----------------------------------------------------------
	 * 搜索结果标签解析
	 * 格式：
	 * <yl:searchOutput pageCount="50" pageNum="10">
	 * </yl:searchOutput>
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param string $attr 标签属性
	 * @param string $content  标签内容
	 +----------------------------------------------------------
	 * @return string|void
	 +----------------------------------------------------------
	 */
	public function _searchOutput($attr,$content) {
		$tag = $this->parseXmlAttr($attr,'searchOutput');
		$parseStr  = $content;
		return $parseStr;
	}
	/**
	 * 解析条件表达式
	 * @access public
	 * @param string $condition 表达式标签内容
	 * @return array
	 */
	protected function parseSqlCondition($condition) {
		$condition = str_ireplace(array_keys($this->comparison), array_values($this->comparison), $condition);
		return $condition;
	}
}
?>